package cn.com.xinjinfu.pdoulcProduct.activity.user;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.IDCardUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.LoginRequestUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.ReloadUserInfo;

/**
 * 实名认证
 * Created by android-adt on 2016/1/7.
 */
public class ActCertification extends BaseActivity implements View.OnClickListener {

    private RequestQueue requen;
    private Button btShiming;
    private TextView tv_error_hint;
    private EditText et_user_name, et_id_num;
    private String id, mobile, pwd;
    /**
     * 实名认证的方式  默认状态 0 为注册时实名认证 1 为其他页面需要实名认证时
     */
    private int cer_style_falg = 0;
    private Dialog dg;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 101:
                    dg.show();
                    TimerTask task = new TimerTask() {
                        public void run() {
                            dg.dismiss();
                            finish();
                        }
                    };
                    Timer timer = new Timer();
                    timer.schedule(task, 1500);
                    break;
            }
        }
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_certification);
        //初始化头布局
        TitleManager.showTitle(this, "实名认证", "");
        ActivityManager.getInstance().addActivity(this);
        requen = Volley.newRequestQueue(this);

        Intent intent = getIntent();
        id = intent.getStringExtra("id");    //取得id
        mobile = intent.getStringExtra("mobile");    //取得手机号
        pwd = intent.getStringExtra("pwd");    //取得密码
        cer_style_falg = intent.getExtras().getInt("cer_style_falg");    //取得实名认证的方式

        if (cer_style_falg == 1) {
            User user = AccountManager.getInstance().getUser();
            if (user != null) {
                id = user.getCurrUser().getSign();}
        }
        et_user_name = (EditText) findViewById(R.id.et_user_name);
        et_id_num = (EditText) findViewById(R.id.et_id_num);
        tv_error_hint = (TextView) findViewById(R.id.tv_error_hint);
        btShiming = (Button) findViewById(R.id.bt_shiming);
        btShiming.setOnClickListener(this);

    }

    /**
     * 注意：点击返回键  通过登录后 跳转到 首页
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        String userName = et_user_name.getText().toString();
        String iDName = et_id_num.getText().toString();
        if (userName.equals("") || iDName.equals("")) {
            tv_error_hint.setText("您输入的身份证号码格式有误，请重新输入");
        } else {
            if (nameJiaoYan(userName)) {
                tv_error_hint.setText("您输入的姓名格式有误，请重新输入");
            } else {
                boolean d = new IDCardUtils().verify(iDName);
                if (d) {
                    loginRequest();
                } else {
                    tv_error_hint.setText("您输入的身份证号有误，请重新输入");
                }
            }
        }
    }

    /**
     * 名字为存汉字时返回false
     *
     * @param s
     */
    public boolean nameJiaoYan(String s) {
        Pattern p = Pattern.compile("[^·\u4e00-\u9fa5]");
        Matcher m = p.matcher(s);
        return m.find();
    }

    /**
     * 此处是为了 区分 注册完成 实名认证时的 返回 跳转
     */
    @Override
    public void onBackPressed() {
        if (cer_style_falg == 1) {
            finish();
        } else if (cer_style_falg == 0) {
            new LoginRequestUtils(ActCertification.this).loginRequest(requen, mobile, pwd);
        }
    }

    /**
     * 实名认证网络请求
     */
    private void loginRequest() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        final Map<String, String> parameters = DataHandler.getParameters("1304");
        parameters.put("id", id);
        parameters.put("realName", et_user_name.getText().toString());
        parameters.put("idNumber", et_id_num.getText().toString());
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
        requen.add(request);
    }
    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(ActCertification.this, error);
        }
    };
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            dg.dismiss();
            if (JSONManager.getError(jobj) == -1) {
                if (cer_style_falg == 0) {
                    /**  注册时 *实名认证成功后 *实现自动登录 *mobile*pwd 是注册页传过来的数据*/
                    UIManager.showSuccessDilog(ActCertification.this, R.drawable.img_douhappy, 0, "恭喜您实名认证成功！", "确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new LoginRequestUtils(ActCertification.this).loginRequest(requen, mobile, pwd);
                        }
                    });

                } else if (cer_style_falg == 1) {
                    TimerTask task = new TimerTask() {
                        public void run() {
                            new ReloadUserInfo(ActCertification.this).userRequest();
                        }
                    };
                    Timer timer = new Timer();
                    timer.schedule(task, 1500);

                    UIManager.showSuccessDilog(ActCertification.this, R.drawable.img_douhappy,0, "恭喜您实名认证成功！", "确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Message msg = new Message();
                            msg.what = 101;
                            handler.sendMessage(msg);
                        }
                    });
                }
            }else {
                UIManager.showSuccessDilog(ActCertification.this, R.drawable.img_doucry,1, JSONManager.getMsg(jobj), "确定", null);
            }
        }
    };

}
